//
//  ZHViewController.swift
//  仿苹果首页动画
//
//  Created by slience on 2019/8/20.
//  Copyright © 2019 shehuiren. All rights reserved.
//

import UIKit


class ZHViewController: UIViewController {

    var bgImage : UIImage?
    var imageName : String?
    var selectIndexPath : IndexPath?
    var isHorizontal : Bool?
    var startPointY : CGFloat?
    var startPointX : CGFloat?
    var scale : CGFloat?
    var titleStr1: String?
    var titleStr2: String?
     var des: String?
    
    @IBOutlet weak var myScrollView : UIScrollView!
    @IBOutlet weak var  headImageView: UIImageView!
    @IBOutlet weak var content : UILabel!
    @IBOutlet weak var bgView : UIView!
    @IBOutlet weak var title1 : UILabel!
    @IBOutlet weak var title2 : UILabel!
    
    
   private var titleLabel : UILabel?{
        
        let lable = UILabel(frame: CGRect(x: 15, y: 15, width: SCREEN_WIDTH-30, height: 21))
        lable.text = titleStr1
        
        lable.textColor = .white
        lable.font = UIFont.systemFont(ofSize: 20, weight: .medium)

        return lable
    }
   private var titleTwoLabel : UILabel?{
        
        let lable = UILabel(frame: CGRect(x: 15, y: (SCREEN_WIDTH-20*2)*1.5-30, width: SCREEN_WIDTH - 40 - 30, height: 21))
        lable.text = titleStr2
        
        lable.textColor = .white
        lable.font = UIFont.systemFont(ofSize: 18, weight: .medium)
        return lable
    }
    
    

    override func viewDidLoad() {
        super.viewDidLoad()
        
       navigationController?.delegate = self
       setEffect()
       headImageView.image = UIImage(named: imageName ?? "")
       title1.text = titleStr1
       title2.text = titleStr2
       content.text = des
        //加手势
        let pan = UIPanGestureRecognizer(target: self, action: #selector(pan(panGesture:)))
        pan.delegate = self
        myScrollView.addGestureRecognizer(pan)
    }
    //MARK: - - 制作毛玻璃背景
    func setEffect (){
        let bgImgV = UIImageView(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: SCREEN_HEIGHT))
        
        view.insertSubview(bgImgV, at: 0)
        
        bgImgV.image = bgImage
        
        let effect = UIBlurEffect(style: .light)
        
        let effectView = UIVisualEffectView(effect: effect)
        
        effectView.frame = CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: SCREEN_HEIGHT)
        
        view.insertSubview(effectView, aboveSubview: bgImgV)
    }
    //MARK: - -隐藏状态栏
    override var prefersStatusBarHidden: Bool{
        
        return true
    }
    //MARK: - -添加手势
    @objc func pan(panGesture : UIPanGestureRecognizer){
        
        switch panGesture.state {
        case .began:
            let currentPoint = panGesture.location(in: myScrollView)
            startPointY = currentPoint.y
            startPointX = currentPoint.x
            if startPointX! > CGFloat(50.0){
                isHorizontal = false
            }else{
                isHorizontal = true
            }
            break
        case .changed :
            
            let currentPoint = panGesture.location(in: myScrollView)
            
            if  isHorizontal == true{
                
                if (currentPoint.x - startPointX!) > (currentPoint.y - startPointY!){
                    
                    scale = (SCREEN_WIDTH-(currentPoint.x-startPointX!))/SCREEN_WIDTH
                }else{
                    
                    scale = (SCREEN_HEIGHT-(currentPoint.y-startPointY!))/SCREEN_HEIGHT
                }
            }else{
                scale = (SCREEN_HEIGHT-(currentPoint.y-startPointY!))/SCREEN_HEIGHT
            }
            
            if scale! > CGFloat(1.0) {
                
                scale = 1.0
            }else if scale! <= CGFloat(0.8) {
                scale = 0.8
                
                DispatchQueue.main.asyncAfter(deadline: DispatchTime(uptimeNanoseconds: UInt64(0.03))) {
                    
                    self.navigationController?.popViewController(animated: true)
                }
                
                
                //
                
            }
            
            // 初始开始 根据scale的变小 myTableView.contentOffset.y 也越来越小
            if myScrollView.contentOffset.y <= 0 {
                
                bgView.transform = CGAffineTransform.init(scaleX: scale!, y: scale!)
                
                bgView.layer.masksToBounds = true
                bgView.layer.cornerRadius = 15/20*(1-scale!)*100//15 * (1-scale!)*5*1.08
                
            }
            
            // 手指滑动的时候 停止列表 滚动 防止tableview上的内容滚动
            if scale! < 0.99{
                myScrollView.isScrollEnabled = false
            } else {
                myScrollView.isScrollEnabled = true
            }
            
            break
            
        case .ended:
            
            scale = 1.0
            myScrollView.isScrollEnabled = true
            
            if scale! > 0.8 {
                
                UIView.animate(withDuration: 0.2) {[weak self]in
                    
                    self?.bgView.layer.cornerRadius = 0
                    
                    self?.bgView.transform = CGAffineTransform.init(scaleX: 1.0, y: 1.0)
                    
                }
            }
            
            break
        default:
            
            
            
            break
            
        }
    }
    

   

}

extension ZHViewController : UINavigationControllerDelegate,UIViewControllerAnimatedTransitioning,UIGestureRecognizerDelegate{
    
    func navigationController(_ navigationController: UINavigationController, animationControllerFor operation: UINavigationController.Operation, from fromVC: UIViewController, to toVC: UIViewController) -> UIViewControllerAnimatedTransitioning?{
        
        
        return self
    }
    
    //MARK: - -手势只有在UIScrollView上识别
    func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool{
        
        if let onView  = otherGestureRecognizer.view, onView.isKind(of: UIScrollView.self){
            
            return true
        }
        
        return false
    }
    //MARK: - -动画时长
    func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
        
        return 1.0
    }
     //MARK: - -核心动画
    func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
        
        // 从这里
        let fromVC = transitionContext.viewController(forKey: .from) as! ZHViewController
        //到这里
        let toVC = transitionContext.viewController(forKey: .to) as! HomePageVC
        //从这个vc
        let fromView = headImageView
        //临时容器 这里有个重要的概念containerView，要做转场动画的视图就必须要加入containerView上才能进行，可以理解containerView管理着所有做转场动画的视图
        let containerView = transitionContext.containerView
        
        var  cell : HomePageCell?
        
        if let index = selectIndexPath{
            
            cell = toVC.myTableView.cellForRow(at: index) as? HomePageCell
        }
        let toView = cell?.header
        
        //截屏
        let snapShotView = fromView?.snapshotView(afterScreenUpdates: false)
        
        snapShotView?.layer.masksToBounds = true
        snapShotView?.layer.cornerRadius = 15
        
        snapShotView?.frame  = containerView.convert(fromView!.frame, from: fromView?.superview)
        
        // 加载到临时容器 让跳转动画有痕迹
        containerView.insertSubview(toVC.view, belowSubview: fromVC.view)
        
        containerView.addSubview(snapShotView!)
        
        //title
        snapShotView?.addSubview(titleLabel!)
        snapShotView?.addSubview(titleTwoLabel!)
        
        toView?.isHidden = true
        fromView?.isHidden = true
        
        
        UIView.animate(withDuration: self.transitionDuration(using: transitionContext), delay: 0, usingSpringWithDamping: 0.5, initialSpringVelocity: 0.8, options: .curveEaseInOut, animations: {
            
            containerView.layoutIfNeeded()
            self.myScrollView.layoutIfNeeded()
            fromVC.view.alpha = 0.0
            snapShotView?.layer.cornerRadius = 15
            self.myScrollView.frame = CGRect(x:  self.myScrollView.frame.origin.x, y:  self.myScrollView.frame.origin.y, width:  self.myScrollView.frame.size.width, height: SCREEN_WIDTH*1.5*0.8)
            self.myScrollView.layer.cornerRadius = 15
            snapShotView?.frame = containerView.convert(toView!.frame, from: toView?.superview)//临时的 
            
            
        }) { (finish) in
            
            fromView?.isHidden = true
            snapShotView?.removeFromSuperview()
            toView?.isHidden = false
            transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
        }
        
        
        
    }
    
    
    
}
extension ZHViewController:UIScrollViewDelegate{
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        
        if scrollView.contentOffset.y <= 0 {
            
          scrollView.contentOffset.y = 0
//            var rectQ = self.headImageView?.frame
//            rectQ?.origin.y = scrollView.contentOffset.y
//            self.headImageView?.frame = rectQ!
          
        }
    }
}
